<template>
  <panel title="工厂维修工单创建">
    <el-form class="form-horizontal"
             :model="workOrderDto"
             :rules="workOrderRules"
             label-width="120px"
             ref="workOrderForm">
      <el-form-item label="维修人">
        <el-input v-model="workOrderDto.repairer" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="型号">
        <el-input v-model="workOrderDto.model" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="YSTSN">
        <el-input v-model="workOrderDto.ystsn" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="是否更新YSTSN" v-if="workOrderDto.ystsn.substring(0,4) !== 'A000'">
        <el-radio-group v-model.number="workOrderDto.isUpdate" @change="onchange()">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="新YSTSN" v-if="workOrderDto.ystsn.substring(0,4) === 'A000'">
        <el-input v-model="workOrderDto.newYstsn" placeholder="请输入新的YSN"></el-input>
      </el-form-item>
      <el-form-item label="更新后的YSN" v-if="workOrderDto.isUpdate === 1" prop="updateAfterYstsn">
        <el-input v-model="workOrderDto.updateAfterYstsn" placeholder="请输入更新后的YSN"></el-input>
      </el-form-item>
      <el-form-item label="更新YSN说明" v-if="workOrderDto.isUpdate === 1" prop="updateCause">
        <el-input v-model="workOrderDto.updateCause" placeholder="请输入更新YSTSN的说明"></el-input>
      </el-form-item>
      <el-form-item label="责任归属" prop="duty">
        <el-select v-model="workOrderDto.duty" placeholder="请选择责任归属" @change="onDutyChange">
          <el-option
            v-for="item in dutyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="故障分类" prop="faultType">
        <el-select v-model="workOrderDto.faultType" placeholder="请选择故障分类" @change="onFaultTypeChange">
          <el-option
            v-for="item in faultTypeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="故障现象" prop="faultAppearance">
        <el-select v-model="workOrderDto.faultAppearance" @change="changeFaultAppearance">
          <el-option
            v-for="item in allFaultAppearance"
            :key="item.id"
            :label="item.appearance"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="故障处理" prop="faultTreatment" v-if="workOrderDto.faultType != 4">
        <el-select v-model="workOrderDto.faultTreatment" placeholder="请选择故障处理方式" @change="faultTreatmentChange">
          <el-option
            v-for="item in repairTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="更换部件" v-if="workOrderDto.faultTreatment === 2 && workOrderDto.faultType === 1">
        <el-card class="box-card">
          <div slot="header">
            <el-button type="text" @click="onBtnAddMaterial"
                       :disabled="workOrderDto.faultTreatment == '6' || workOrderDto.faultTreatment == '7'">添加部件
            </el-button>
            <el-button type="text" @click="onBtnDelMaterial"
                       :disabled="workOrderDto.faultTreatment == '6' || workOrderDto.faultTreatment == '7'">删除部件
            </el-button>
          </div>
          <el-row :gutter="5" v-for="o in this.materielCount" :key="o">
            <el-col :span="6">
              <el-input placeholder="更换部件品牌"
                        v-model="workOrderDto.materielBrand[o]"
                        :disabled="workOrderDto.faultTreatment == '6' || workOrderDto.faultTreatment == '7'"></el-input>
            </el-col>
            <el-col :span="6">
              <el-input v-model="workOrderDto.materielModel[o]" auto-complete="off" placeholder="更换部件型号"
                        :disabled="workOrderDto.faultTreatment == '6' || workOrderDto.faultTreatment == '7'"></el-input>
            </el-col>
            <el-col :span="6">
              <el-input v-model="workOrderDto.badNumber[o]" auto-complete="off" placeholder="更换不良位号"
                        :disabled="workOrderDto.faultTreatment == '6' || workOrderDto.faultTreatment == '7'"></el-input>
            </el-col>
            <el-col :span="6">
              <el-input v-model.number="workOrderDto.num[o]" auto-complete="off" placeholder="更换部件数量"
                        :disabled="workOrderDto.faultTreatment == '6' || workOrderDto.faultTreatment == '7'"></el-input>
            </el-col>
          </el-row>
        </el-card>
      </el-form-item>
      <el-form-item label="维修结果" prop="repairResult">
        <el-select :disabled="workOrderDto.faultTreatment == '6' || workOrderDto.faultTreatment == '7' ||
                   workOrderDto.faultType == 4" v-model="workOrderDto.repairResult" placeholder="请选择维修结果">
          <el-option
            v-for="item in resultOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上传附件" v-if="workOrderDto.repairResult === 4">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :headers="myHeaders"
          name="file"
          :on-error="uploadError"
          :on-success="uploadSuccess"
          :before-upload="beforeAvatarUpload"
          multiple
          drag
          :limit="1"
          :file-list="fileList">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-form-item>

      <!--选择备注说明-->
      <el-form-item label="原因说明" v-if="workOrderDto.repairResult === 3 || workOrderDto.repairResult === 4">
        <el-input v-model="workOrderDto.description" placeholder="请填写待报废或原物返还的原因"></el-input>
      </el-form-item>
      <!--v-no-more-click为防止重复提交指令-->
      <el-button type="primary" @click="onBtnSubmit()" style="float: right;" v-no-more-click>提交</el-button>
    </el-form>
  </panel>
</template>

<script>
  import Panel from '@/components/common/Panel'
  import {baseInfo} from '@/utils/fetch'
  import store from '@/store'
  import {
    apiGetFaultTypeList,
    apiGetFaultAppearanceList,
    apiGetFaultAppearanceCode,
    // apiGetMaterielListByModelId,
    apiGetFaultAppearance
  } from '@/api/dictionary'
  import {apiPostFactoryRepair} from '@/api/repairs/factory/index'
  import {getName} from '@/utils/token'
  import {apiGetFaultById} from '@/api/basic/info/fault'
  import {getUserId} from '../../../utils/token'

  export default {
    components: {Panel},
    data () {
      return {
        // 导入上传url
        uploadUrl: baseInfo() + '/api/v1/upload',
        // 导入上传头部
        myHeaders: {'access_token': store.getters.token},
        // 上传文件显示
        fileList: [],
        // 文件上传路径
        importFileUrl: baseInfo() + '/api/v1/upload',
        // 文件上传参数
        upLoadData: {},
        dutyOptions: [
          {value: '客户', label: '客户'},
          {value: '维修点', label: '维修点'},
          {value: '工厂', label: '工厂'},
          {value: '材料不良', label: '材料不良'}
        ],
        faultTypeOptions: [],
        faultAppearanceOptions: [],
        repairTypeOptions: [],
//        materielOptions: [],
        allFaultAppearance: [],
        hardwareRepairType: [
          {value: 2, label: '更换部件'},
          {value: 6, label: '原物返还'},
          {value: 7, label: '待报废'}
        ],
        softwareRepairType: [
          {value: 3, label: '刷机'},
          {value: 4, label: '升级'},
          {value: 5, label: '恢复出厂'}
        ],
        resultOptions: [
          {value: 2, label: '已修复'},
          {value: 3, label: '原物返还'},
          {value: 4, label: '待报废'}
        ],
        dutyHardwareRepairType: [
          {value: 2, label: '更换部件'},
          {value: 6, label: '原物返还'},
          {value: 7, label: '待报废'},
          {value: 10, label: '假焊'},
          {value: 11, label: '少锡'},
          {value: 12, label: '加焊'},
          {value: 13, label: '偏移'},
          {value: 14, label: '少件'}
        ],
        materielDto: {
          modelId: this.$route.query.modelId
        },
        workOrderDto: {
          repairerId: getUserId(),
          repairer: getName(),
          model: this.$route.query.model,
          modelId: this.$route.query.modelId,
          brandId: this.$route.query.brandId,
          batch: this.$route.query.batch,
          ystsn: this.$route.query.ystsn,
          newYstsn: '',
          isUpdate: 0, // 是否更新ystsn码
          updateAfterYstsn: '', // 更新的ystsn
          updateCause: '', // 更新ystsn说明
          duty: '',
          faultType: '',   // 故障类型
          faultAppearance: '',
          isMateriel: '',  // 是否用料
          // 更换配件标志量(用于判断更换配件时是否输入配件品牌和型号)
          brandAndModelFlag: true,
          faultTreatment: '',   // 故障处理方式
          description: '', // 备注说明
          num: [], // 更换部件数量
          materiel: [], // 更换部件(由品牌-型号-不良位号拼接而成)
          materielBrand: [], // 更换部件品牌
          materielModel: [], // 更换部件型号
          badNumber: [], // 更换不良位号
          replaceParts: '',
          repairResult: '',
          reason: '',
          status: this.$route.query.lastDevice,
          proposer: getName(),
          filePath: ''
        },
        uploadVisible: false,
        materielCount: 1,
        loading: false,
        workOrderRules: {
          updateAfterYstsn: [
            {required: true, message: '请输入新的YSN', trigger: 'blur'},
            {max: 32, message: '长度不超过 32', trigger: 'blur'}
          ],
          updateCause: [
            {required: true, message: '请输入更新YSTSN的说明', trigger: 'blur'}
          ],
          duty: [
            {required: true, message: '请选择责任人', trigger: 'change'}
          ],
          faultType: [
            {type: 'number', required: true, message: '请选择故障类型', trigger: 'change'}
          ],
          faultTreatment: [
            {type: 'number', required: true, message: '请选择故障处理方式', trigger: 'change'}
          ],
          repairResult: [
            {type: 'number', required: true, message: '请选择维修结果', trigger: 'change'}
          ],
          reason: [
            {required: true, message: '请输入报废原因', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      uploadSuccess (response) {
        this.workOrderDto.filePath = response.data
        this.$message({
          showClose: true,
          message: '上传成功',
          type: 'success'
        })
      },
      // 上传错误
      uploadError () {
        this.$message({
          showClose: true,
          message: '上传失败，请重试！'
        })
      },
      // 上传前对文件的大小的判断
      beforeAvatarUpload (file) {
        let fileNameArr = file.name.split('.')
        let extension = fileNameArr[fileNameArr.length - 1]
        let isLt2M = file.size / 1024 / 1024 < 10
        let fileType = true
        if (extension !== 'xlsx' && extension !== 'zip') {
          fileType = false
          this.$message({
            showClose: true,
            message: '上传模板只能是 xlsx 或 zip 格式!'
          })
        }
        if (!isLt2M) {
          this.$message({
            showClose: true,
            message: '上传文件大小不能超过 10MB!'
          })
        }
        return fileType && isLt2M
      },
      changeFaultAppearance () {
        this.workOrderDto.faultTreatment = ''
        apiGetFaultById(this.workOrderDto.faultAppearance).then(response => {
          let type = response.data.isMaterial
          if (type === 0) { // 硬件故障
            this.workOrderDto.isMateriel = 0       // 用料
            if (this.workOrderDto.duty == '工厂') {
              // 责任归属为工厂时
              this.repairTypeOptions = this.dutyHardwareRepairType
            } else {
              this.repairTypeOptions = this.hardwareRepairType   // 硬件故障处理方式
            }
            // this.workOrderDto.faultTreatment = this.hardwareRepairType[0].value
            // this.selectMaterielInit()
          } else if (type === 1) {     // 软件故障
            this.workOrderDto.isMateriel = 1   // 不用料
            this.repairTypeOptions = this.softwareRepairType // 软件故障处理方式
          }
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      remoteFaultAppearanceMethod (query) {
        let ch = /^[\u4E00-\u9FFF]+$/
        let en = /^[A-Za-z0-9]+$/
        if (query !== '' && this.workOrderDto.faultType !== '' && (ch.test(query) || en.test(query))) {
          this.loading = true
          setTimeout(() => {
            this.loading = false
            let type = ch.test(query) ? 1 : 0
            let listQuery = {
              query: query.toUpperCase(),
              faultType: this.workOrderDto.faultType,
              type: type,
              isMateriel: this.workOrderDto.isMateriel
            }
            apiGetFaultAppearanceCode(listQuery).then(response => {
              this.faultAppearanceOptions = response.data
            }).catch(() => {
              this.tableLoadingFlag = false
            })
          }, 200)
        } else {
          this.faultAppearanceOptions = []
        }
      },
      // 切换单选框，重置数据
      onchange () {
        this.workOrderDto.updateAfterYstsn = ''
        this.workOrderDto.updateCause = ''
      },
      // 物料选择初始化
      // selectMaterielInit() {
      //   apiGetMaterielListByModelId(this.$route.query.modelId).then(response => {
      //     let materielList = response.data
      //     let materiel = []
      //     let temp = {}
      //     for (let i in materielList) {
      //       if (!temp[materielList[i].name]) {
      //         temp[materielList[i].name] = materielList[i].id
      //       }
      //     }
      //     for (let k in temp) {
      //       materiel.push({'name': k, 'id': temp[k]})
      //     }
      //     this.materielOptions = materiel
      //   }).catch(() => {
      //     this.tableLoadingFlag = false
      //   })
      // },
      // 故障现象初始化
      selectFaultAppearanceInit (listQuery) {
        apiGetFaultAppearanceList(listQuery).then(response => {
          let faultAppearanceList = response.data
          let faultAppearance = []
          let temp = {}
          for (let i in faultAppearanceList) {
            if (!temp[faultAppearanceList[i].name]) {
              temp[faultAppearanceList[i].name] = faultAppearanceList[i].id
            }
          }
          for (let k in temp) {
            faultAppearance.push({'name': k, 'id': temp[k], 'code': k})
          }
          this.faultAppearanceOptions = faultAppearance
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      getFaultAppearance (faultDto) {
        apiGetFaultAppearance(faultDto).then(response => {
          this.allFaultAppearance = response.data
        })
      },
      // 故障类型选择初始化
      selectFaultTypeInit () {
        apiGetFaultTypeList().then(response => {
          let faultTypeList = response.data
          let faultType = []
          let temp = {}
          for (let i in faultTypeList) {
            if (!temp[faultTypeList[i].name]) {
              temp[faultTypeList[i].name] = faultTypeList[i].id
            }
          }
          for (let k in temp) {
            faultType.push({'name': k, 'id': temp[k]})
          }
          this.faultTypeOptions = faultType
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // 责任归属
      onDutyChange (type) {
        this.workOrderDto.faultAppearance = ''
        this.workOrderDto.faultType = ''
        this.workOrderDto.isMateriel = ''
        this.workOrderDto.faultTreatment = ''
        this.workOrderDto.duty = type
      },
      onFaultTypeChange () {
        this.workOrderDto.faultAppearance = ''
        this.workOrderDto.isMateriel = ''
        this.workOrderDto.faultTreatment = ''
        this.repairTypeOptions = []
        if (this.workOrderDto.faultType === 4) {
          this.workOrderDto.repairResult = 2
        } else {
          this.workOrderDto.repairResult = ''
        }
        let faultDto = {
          faultType: this.workOrderDto.faultType
        }
        this.getFaultAppearance(faultDto)
        // this.workOrderDto.faultAppearance = ''
        // this.workOrderDto.faultTreatment = ''
        // this.workOrderDto.faultType = type
        // let listQuery = {
        //   brandId: this.$route.query.brandId,
        //   faultType: type
        // }
        // this.selectFaultAppearanceInit(listQuery)
        // if (type === 1 || type === 3) {                               // 硬件故障
        //   this.workOrderDto.isMateriel = 0       // 用料
        //   this.workOrderDto.faultTreatment = this.hardwareRepairType[0].value
        //   this.repairTypeOptions = this.hardwareRepairType   // 硬件故障处理方式
        //   this.selectMaterielInit()
        // } else if (type === 2 || type === 4) {     // 软件故障
        //   this.workOrderDto.isMateriel = 1   // 不用料
        //   this.repairTypeOptions = this.softwareRepairType // 软件故障处理方式
        // }
      },
      // 格式化配件信息并对配件品牌、型号为必选进行校验
      formatMateriel () {
        if (this.workOrderDto.materielBrand.length > 0) {
          for (let i = 1; i <= this.materielCount; i++) {
            if (this.workOrderDto.materielBrand[i] === '' || this.workOrderDto.materielBrand[i] === undefined) {
              this.$message({
                showClose: true,
                message: '配件品牌不可以为空',
                type: 'error'
              })
              this.workOrderDto.brandAndModelFlag = false
              return
            } else if (this.workOrderDto.materielModel[i] === '' || this.workOrderDto.materielModel[i] === undefined) {
              this.$message({
                showClose: true,
                message: '配件型号不可以为空',
                type: 'error'
              })
              this.workOrderDto.brandAndModelFlag = false
              return
            } else {
              this.workOrderDto.materiel[i] = this.workOrderDto.materielBrand[i] + '-' + this.workOrderDto.materielModel[i] + '-' + this.workOrderDto.badNumber[i]
            }
          }
        }
      },
      onBtnSubmit () {
        this.$refs['workOrderForm'].validate((valid) => {
          let materielFlag = false
          if (this.workOrderDto.faultTreatment == '2') {
            this.workOrderDto.replaceParts = '{'
            this.formatMateriel()
            // 对更换的配件品牌和型号，进行校验
            if (this.workOrderDto.brandAndModelFlag) {
              if (this.workOrderDto.materiel.length > 0) {
                for (let i in this.workOrderDto.materiel) {
                  if (this.workOrderDto.materiel[i] == undefined || this.workOrderDto.num[i] == undefined) {
                    materielFlag = true
                  }
                  this.workOrderDto.replaceParts += '"' + this.workOrderDto.materiel[i] + '":"' + this.workOrderDto.num[i] + '"'
                  if (i < this.workOrderDto.materiel.length - 1) {
                    this.workOrderDto.replaceParts += ','
                  }
                }
                this.workOrderDto.replaceParts += '}'
              } else {
                materielFlag = true
              }
            } else {
              // 存在更换配件中的品牌或型号未填写，则不通过
              this.workOrderDto.brandAndModelFlag = true
              return false
            }
          }
          let ystsnFlag = false
          if (this.workOrderDto.ystsn.substring(0, 4) === 'A000' && this.workOrderDto.newYstsn === '') {
            ystsnFlag = true
          }
          if (materielFlag) {
            this.$message({
              showClose: true,
              message: '物料信息填写不完整',
              type: 'error'
            })
          } else if (ystsnFlag) {
            this.$message({
              showClose: true,
              message: '请为本台设备添加新的YSN条形码',
              type: 'error'
            })
          } else if (valid) {
            if (this.workOrderDto.repairResult === 3) {
              if (this.workOrderDto.description) {
                this.showPostFactoryRepair()
              } else {
                this.$message({
                  showClose: true,
                  message: '备注信息不完整',
                  type: 'error'
                })
              }
            } else if (this.workOrderDto.repairResult === 4) {
              if (this.workOrderDto.description) {
                if (this.workOrderDto.filePath) {
                  // 已上传附件，进行提交
                  this.showPostFactoryRepair()
                } else {
                  // 未上传附件，通过message提示用户上传附件
                  this.$message({
                    showClose: true,
                    message: '请上传文件',
                    type: 'error'
                  })
                }
              } else {
                this.$message({
                  showClose: true,
                  message: '备注信息不完整',
                  type: 'error'
                })
              }
            } else if (this.workOrderDto.repairResult === 2) {
              this.showPostFactoryRepair()
            }
          } else {
            return false
          }
        })
      },
      showPostFactoryRepair () {
        apiPostFactoryRepair(this.workOrderDto).then(() => {
          this.$message({
            showClose: true,
            message: '提交成功',
            type: 'success'
          })
          this.$router.push({
            path: '/repairs/factory/repairs'
          })
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // 添加部件
      onBtnAddMaterial () {
        this.materielCount = this.materielCount + 1
      },
      // 删除部件
      onBtnDelMaterial () {
        if (this.materielCount > 1) {
          this.clearMaterial(this.materielCount)
          this.materielCount = this.materielCount - 1
        }
      },
      // 当点击删除部件时，清空被删除部件的信息
      clearMaterial (i) {
        this.workOrderDto.materielBrand[i] = ''
        this.workOrderDto.materielModel[i] = ''
        this.workOrderDto.badNumber[i] = ''
        this.workOrderDto.num[i] = ''
      },
      // 故障处理方式
      faultTreatmentChange () {
        if (this.workOrderDto.faultTreatment == '6') {  // 原物返还
          this.workOrderDto.repairResult = 3
        } else if (this.workOrderDto.faultTreatment == '7') {  // 待报废
          this.workOrderDto.repairResult = 4
        } else {
          this.workOrderDto.repairResult = ''
        }
      }
      // selectMateriel() {
      //   this.workOrderDto.faultTreatment = ''
      //   if (this.workOrderDto.isMateriel === 0) {
      //     this.repairTypeOptions = this.hardwareRepairType
      //     // this.selectMaterielInit()
      //   } else {
      //     this.repairTypeOptions = this.softwareRepairType
      //   }
      // }
    },
    mounted () {
      this.selectFaultTypeInit()
    }
  }
</script>

<style lang="scss" scoped>
  .el-row {
    margin-bottom: 5px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .box-card {
    width: 516px;
  }
</style>
